package cease.urs;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import cease.http.HttpRequestExecutor;
import cease.http.HttpRequestResult;

/**
 * @author dhf
 */
public class Loginer {
    private static HttpRequestExecutor executor = new HttpRequestExecutor();

    private static String url = "http://reg.163.com/services/userlogin";

    /**
     * 登录
     * 
     * @param username
     * @param password
     * @return 登录成功返回Session，密码错误返回null
     * @throws LoginException
     */
    public static Session login(String username, String password)
            throws LoginException {
        List<NameValuePair> pairs = new LinkedList<NameValuePair>();
        pairs.add(new BasicNameValuePair("username", username));
        pairs.add(new BasicNameValuePair("password", password));
        // 是否设置cookie，0：否；1：是
        pairs.add(new BasicNameValuePair("type", "1"));
        pairs.add(new BasicNameValuePair("product", "t"));
        pairs.add(new BasicNameValuePair("savelogin", "0"));
        // 密码是否md5处理后的，0：是;1：否
        pairs.add(new BasicNameValuePair("passtype", "1"));
        try {
            HttpRequestResult result = executor.post(url, pairs, null, null);
            if (result.getLines().size() > 0) {
                String retCode = result.getLines().get(0);
                if ("201".equals(retCode)) {
                    return Session.parseSetCookies(result.getHeaders());
                } else if ("401".equals(retCode)) {
                    throw new LoginException("parameter format not correct");
                } else if ("412".equals(retCode)) {
                    throw new LoginException("wrong time exceed limit");
                } else if ("420".equals(retCode)) {
                    throw new LoginException("user not found");
                } else if ("422".equals(retCode)) {
                    throw new LoginException("user locked");
                } else if ("460".equals(retCode)) {
                    return null;
                } else {
                    throw new LoginException("urs server error");
                }
            }
            throw new LoginException("urs server error");
        } catch (IOException e) {
            throw new LoginException(e);
        }

    }

    public static void main(String[] args) throws LoginException {
        Session s = login("test@vip.163.com", "password");
        if (null != s) {
            System.out.println(s.getCookieStr());
        } else {
            System.out.println(s);
        }
    }
}
